const { app, BrowserWindow } = require("electron");
const { spawn, exec } = require("child_process");
const path = require("path");

let mainWindow;
let flaskProcess;

function killFlaskProcesses() {
    exec('pkill -f flask_server', (error, stdout, stderr) => {
        if (error) {
            console.error(`Error killing Flask processes: ${error}`);
            return;
        }
        console.log(`Killed Flask processes: ${stdout}`);
    });
}


function startFlask() {

    const flaskExecutable = app.isPackaged
    ? path.join(process.resourcesPath, "flask_server")  // 打包后路径
    : path.join(__dirname, "flask_server");  // 开发环境路径

    console.log(flaskExecutable)

    const { spawn } = require("child_process");
    const fs = require("fs");

    if (process.platform === "linux") {
        try {
            fs.chmodSync(flaskExecutable, 0o755);  // 赋予可执行权限
        } catch (err) {
            console.error("Failed to set executable permission for flask_server:", err);
        }
    }

    const flaskProcess = spawn(flaskExecutable, [], { stdio: "inherit" });


    flaskProcess.on('error', (err) => {
        console.error(`Failed to start Flask server: ${err}`);
    });

    flaskProcess.on('close', (code) => {
        console.log(`Flask process exited with code ${code}`);
    });
}

app.whenReady().then(() => {
    startFlask();

    mainWindow = new BrowserWindow({
        width: 1050,
        height: 850,
        webPreferences: {
            nodeIntegration: true
        },
        autoHideMenuBar: true // Hide the menu bar
    });

    // Add a delay before loading the URL
    setTimeout(() => {
        mainWindow.loadURL("http://127.0.0.1:5000");
    }, 5000);

    mainWindow.on('closed', () => {
        killFlaskProcesses();
        mainWindow = null;
    });
});



app.on("window-all-closed", () => {
    killFlaskProcesses();
    app.quit();
});